//
//  DiscoverJobViewController.m
//  陶瓷
//
//  Created by 郭天龙 on 15/7/29.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "DiscoverJobViewController.h"
#import "TCNetworkTool.h"
#import "DisJobTableViewCell.h"
#import "DisJobSecondTableViewCell.h"
#import "DisJobThirdTableViewCell.h"
#import "TCNavigationItemFavouriteBtn.h"

@interface DiscoverJobViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, weak) IBOutlet UITableView *tableview;
@property (nonatomic, strong) NSDictionary *datadic;

@property (nonatomic, strong) UIButton *topBtn;
@property (nonatomic, strong) UIButton *favorBtn;

@property (nonatomic, strong) UIButton *cover;

@property (nonatomic, strong) BMKMapView *mapView;

@property (strong,nonatomic) BMKLocationService *locService;

@property (nonatomic, assign) CGFloat locaLatitude;
@property (nonatomic, assign) CGFloat locaLongitude;

@end

@implementation DiscoverJobViewController

#pragma mark - Action
- (IBAction)clickFindCompany:(id)sender
{
    //    TailMapViewController *mapvc = [[TailMapViewController alloc] init];
    //    [self.navigationController pushViewController:mapvc animated:YES];
    
    [self initBMKUserLocation];
}

- (IBAction)clickTel:(id)sender
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",[self.datadic objectForKey:@"ContactNumber"]]]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"招聘";
    
    self.tableview.tableFooterView = [UIView new];
    self.tableview.hidden = YES;
    [self.tableview setSeparatorInset:UIEdgeInsetsZero];
    self.tableview.backgroundColor = [UIColor colorWithString:@"#EFEFF4"];
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
    
    [self.tableview registerNib:[UINib nibWithNibName:@"DisJobTableViewCell" bundle:nil] forCellReuseIdentifier:@"DisJobTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"DisJobSecondTableViewCell" bundle:nil] forCellReuseIdentifier:@"DisJobSecondTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"DisJobThirdTableViewCell" bundle:nil] forCellReuseIdentifier:@"DisJobThirdTableViewCell"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(infoChange:) name:@"EditSuccessNotification" object:nil];
    
    
    TCNetworkTool *tctool = [TCNetworkTool sharedNetTool];
    [tctool RecruitmentDetailWithID:self.sid andSuccessBlocks:^(NSDictionary *resultDic) {
        [SVProgressHUD dismiss];
        if (resultDic) {
            self.datadic = [resultDic mutableCopy];
            self.tableview.hidden = NO;
            [self settingDetails];
        }
    } andFailureBlocks:^(NSString *failureMessage) {
        [SVProgressHUD dismiss];
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
    
    [self setupNavigationItem];
    
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationItem setTitle:@"岗位描述"];
    if(!IsLoginIn) {
        _favorBtn.hidden = YES;
    } else {
        if (!_isFavor && _favorBtn) {
            [[TCNetworkTool sharedNetTool] checkIsFavouritesWithType:kTCCollectTypeRecruitment andObjectID:_sid andSuccessBlocks:^(NSString *successMessage) {
                self.isFavor = [successMessage isEqualToString:@"已关注此信息"];
            } andFailureBlocks:^(NSString *failureMessage) {
                if ([failureMessage isEqualToString:@"未关注此信息"]) {
                    self.isFavor = NO;
                }
            }];
        } else {
            self.favorBtn.selected = YES;
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationItem setTitle:@""];
    [self.cover removeFromSuperview];
    [SVProgressHUD dismiss];
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor clearColor];
    }
    return _cover;
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            DisJobTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DisJobTableViewCell"];
            cell = [[NSBundle mainBundle] loadNibNamed:@"DisJobTableViewCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setModel:self.datadic];
            return cell;
        }
            break;
        case 1:
        {
            DisJobSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DisJobSecondTableViewCell"];
            cell = [[NSBundle mainBundle] loadNibNamed:@"DisJobSecondTableViewCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setModel:self.datadic];
            return cell;
        }
            break;
        case 2:
        {
            DisJobThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DisJobThirdTableViewCell"];
            cell = [[NSBundle mainBundle] loadNibNamed:@"DisJobThirdTableViewCell" owner:nil options:nil].firstObject;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setModel:self.datadic];
            return cell;
        }
            break;
            
        default:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"disjob"];
            
            cell = [[UITableViewCell alloc] init];
            return cell;
        }
            break;
    }
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return 120;
            break;
        case 1:
        {
            NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
            style.lineBreakMode = NSLineBreakByWordWrapping;
            
            NSString *tmp = [self.datadic objectForKey:@"Requirements"];
            CGFloat height = 0;
            if (tmp) {
                CGRect lblSize = [tmp boundingRectWithSize:CGSizeMake(kDefaultWindowWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17], NSParagraphStyleAttributeName:style} context:nil];
                
                height = lblSize.size.height;
            }
            
            NSString *tmp1 = [self.datadic objectForKey:@"Address"];
            if (tmp1) {
                CGRect lblSize = [tmp1 boundingRectWithSize:CGSizeMake(kDefaultWindowWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17], NSParagraphStyleAttributeName:style} context:nil];
                
                height += lblSize.size.height;
            }
            
            return 120+height;
        }
            
            break;
        case 2:
            return 110;
            break;
        default:
            return 0;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDefaultWindowWidth, 10)];
        view.backgroundColor = [UIColor colorWithString:@"#EFEFF4"];
        return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)top {
    [SVProgressHUD showWithStatus:@"正在发送置顶请求 请稍后.."];
    [self.view addSubview:self.cover];
    [[TCNetworkTool sharedNetTool] recruitmentTopWithID:self.sid andSuccessBlocks:^(NSString *successMessage) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:@"置顶成功!"];
        [_topBtn setTitle:@"已置顶" forState:UIControlStateNormal];
        [_topBtn sizeToFit];
        _topBtn.userInteractionEnabled = NO;
        [self.cover removeFromSuperview];
    } andFailureBlocks:^(NSString *failureMessage) {
        [SVProgressHUD dismiss];
        [self.cover removeFromSuperview];
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
}

- (void)edit {
    AddMessageController *addMessage = [[AddMessageController alloc] init];
    addMessage.questionArray = recruitmentQuestionArray;
    addMessage.sid = self.datadic[@"Id"];
    addMessage.title = @"招聘信息发布";
    addMessage.answerDict = [@{
                               @"0" : self.datadic[@"Title"] ? self.datadic[@"Title"] : @"",
                               @"1" : self.datadic[@"CompanyName"] ? self.datadic[@"CompanyName"] : @"",
                               @"2" : self.datadic[@"CompanyScale"] ? self.datadic[@"CompanyScale"] : @"",
                               @"3" : self.datadic[@"CompanyFeature"] ? self.datadic[@"CompanyFeature"] : @"",
                               @"4" : self.datadic[@"ContactNumber"] ? self.datadic[@"ContactNumber"] : @"",
                               @"5" : self.datadic[@"Wage"] ? self.datadic[@"Wage"] : @"",
                               @"6" : self.datadic[@"Address"] ? self.datadic[@"Address"] : @"",
                               @"7" : self.datadic[@"Position"] ? self.datadic[@"Position"] : @"",
                               @"8" : self.datadic[@"Requirements"] ? self.datadic[@"Requirements"] : @""
                               } mutableCopy];
    
    [self.navigationController pushViewController:addMessage animated:YES];
}

#pragma mark - BMKLocationServiceDelegate
/**
 *  初始化百度地图用户位置管理类
 */
- (void)initBMKUserLocation
{
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [self startLocation];
}

/**
 *  打开定位服务
 */
-(void)startLocation
{
    [_locService startUserLocationService];
}

/**
 *  关闭定位服务
 */
-(void)stopLocation
{
    [_locService stopUserLocationService];
}


//-(void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation{
//    NSLog(@"latitude--%f,longtitude---%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    self.locaLatitude=userLocation.location.coordinate.latitude;//纬度
//    self.locaLongitude=userLocation.location.coordinate.longitude;//精度
//}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation;
{
    self.locaLatitude = userLocation.location.coordinate.latitude;
    self.locaLongitude = userLocation.location.coordinate.longitude;
    [self stopLocation];//(如果需要实时定位不用停止定位服务)
    [self mapViewWillStartLocatingUser:nil];
}

-(void)mapViewWillStartLocatingUser:(BMKMapView *)mapView{
    NSLog(@"开始定位");
    BMKOpenTransitRouteOption *opt = [[BMKOpenTransitRouteOption alloc] init];
    opt.appScheme = @"baidumapsdk://mapsdk.baidu.com";//用于调起成功后，返回原应用
    //初始化起点节点
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    //指定起点经纬度
    CLLocationCoordinate2D coor1;
    coor1.latitude = self.locaLatitude;
    coor1.longitude = self.locaLongitude;
    //指定起点名称
    start.name = @"我的位置";
    start.pt = coor1;
    //指定起点
    opt.startPoint = start;
    
    //初始化终点节点
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = [[self.datadic objectForKey:@"Latitude"] floatValue];
    coor2.longitude = [[self.datadic objectForKey:@"Longitude"] floatValue];
    end.pt = coor2;
    //指定终点名称
    end.name = [self.datadic objectForKey:@"CompanyName"];
    opt.endPoint = end;
    
    //打开地图公交路线检索
    BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapTransitRoute:opt];
}


- (void)setupNavigationItem {
    
    if (_mine) {
        UIButton *topBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        topBtn.frame = CGRectMake(0, 0, 50,30);
        [topBtn setTitle:@"已置顶" forState:UIControlStateNormal];
        [topBtn addTarget:self action:@selector(top) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:topBtn];
        _topBtn = topBtn;
        
//        UIButton *editBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//        editBtn.frame = CGRectMake(0, 0, 30,30);
//        [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
//        [editBtn addTarget:self action:@selector(edit) forControlEvents:UIControlEventTouchUpInside];
//        UIBarButtonItem *rightButtonItem2 = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
        
        self.navigationItem.rightBarButtonItems = @[rightButtonItem];
    } else {
        _favorBtn = [TCNavigationItemFavouriteBtn favouriteBtn];
        [_favorBtn addTarget:self action:@selector(favourite) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_favorBtn];
        self.navigationItem.rightBarButtonItem = rightButtonItem;
    }
    
}

// 收藏
- (void)favourite {
    [self.view addSubview:self.cover];
    [[TCNetworkTool sharedNetTool] addFavouritesWithId:nil andUserId:nil andCollectType:kTCCollectTypeRecruitment andTypeID:_sid andAddTime:nil andSuccessBlocks:^(NSString *successMessage) {
        self.isFavor = [successMessage isEqualToString:@"关注成功，可在我的关注中查看"];
        [self.cover removeFromSuperview];
    } andFailureBlocks:^(NSString *failureMessage) {
        [self.cover removeFromSuperview];
    }];
    
}

- (void)setIsFavor:(BOOL)isFavor {
    _isFavor = isFavor;
    _favorBtn.selected = isFavor;
}

- (void)settingDetails {
//    self.title = self.datadic[@"Title"];
    
    BOOL isTop = [self.datadic[@"IsTop"] isEqual:@1];
    NSString *topString = isTop ? @"已置顶" : @"置顶";
    [_topBtn sizeToFit];
    _topBtn.userInteractionEnabled = !isTop;
    [_topBtn setTitle:topString forState:UIControlStateNormal];
    
    [self.tableview reloadData];
}

- (void)infoChange:(NSNotification *)notification {
    [self.datadic setValuesForKeysWithDictionary:notification.object];
    [self settingDetails];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
